/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var xmlCartDoc;
var xslProduct;
var cart;

window.onload = function() {
    xslProduct = loadSourceDoc("xsl", "products.xsl");
    //    xmlCartDoc = loadSourceDoc("xml", "Carts.xml");
    var container = document.getElementById("productlistSearch");
    
    if (!cart) {
        cart=getCart();
        var croot = cart.firstChild;
        var cartNamespace = croot.namespaceURI;
        if (cartNamespace) {
            namespace = cartNamespace;
        }
    }
    transformToCartView();
    //click on Add To Cart
    container.onclick = function(e) {
        var obj = e.target;
        var link = obj.className.split(' ')[2];
        if (link == "linkAddToCart") {
            addToCart(obj);
        }
        if (link == "linkComment") {
            var productId = obj.getAttribute("proID");
            addComment(productId);
        }
    }

    //Cart view container
    var itemContainer = document.getElementById("master-items-container");
    //cart view change when click on Add To Cart
    itemContainer.onchange = function(e) {
        var obj = e.target;
        if (obj.className == "cart-item-quantity") {
            var newQuantity = obj.value;
            var quantity=parseInt(newQuantity);
            var productId;
            var parentRow = getParentByClassName(obj, "cart-item");
            if(parentRow) {
                productId = parentRow.getAttribute("productid");
            }
            if(productId&&quantity&&cart) {
                var orderCart = getSingleNode(cart, "//*[name()='Cart'][*[name()='ProductId']='" + productId + "']");
                var sPrice = orderCart.getElementsByTagName("Price")[0].textContent;
                var price = parseInt(sPrice);
                orderCart.getElementsByTagName("Quantity")[0].textContent = quantity;
                orderCart.getElementsByTagName("TotalPrice")[0].textContent = quantity*price;
                var countNode = getSingleNode(cart, "//*[name()='Count']");
                countNode.textContent=getNumber(cart, "sum(//*[name()='Quantity'])");
                transformToCartView();
            }
        }
    }
    //click on cart view
    itemContainer.onclick=function(e){
        var current=e.target;        
        //click on delete button on cart view
        if(current.className=="cart-item-delete-btn"){
            var prod;
            var pRow=getParentByClassName(current, "cart-item");
            if(pRow){
                prod=pRow.getAttribute("productid");
            }
            if(prod&&cart){
                var root=cart.firstChild;
                var oitem=getSingleNode(cart,"//*[name()='Cart'][*[name()='ProductId']='"+prod+"']");
                if(oitem&&root){

                    root.removeChild(oitem);
                    var cNode=getSingleNode(cart,"//*[name()='Count']");
                    cNode.textContent=getNumber(cart,"sum(//*[name()='Quantity'])");
                    transformToCartView();
                }
            }
        }
        //click on check out button on cart view
        var link = current.className.split(' ');
        if (link.length == 3){
            if(link[2]=="btnCheckOut"){
                var totalMoney=0;
                var totalValue=document.getElementsByClassName("total-payment-sum-value")[0];
                if(totalValue){
                    totalMoney=parseFloat(totalValue.innerHTML);
                }
                if(totalMoney>0){
                    saveCurrentOrderDocToSession(cart);
                    checkOut();
//                    if(!isHaveUserDetail()){
//                        //location.href=contextPath+"/client/Checkout.jsp"
//                    }
//                    else{
//
//                    }
                }
            }
        }
    }  
}

function addComment(productId) {
    var btnClose = document.getElementById("btnClose");
    var container =  document.getElementById("PopupContainer");
    var content = document.getElementById("content");
    var overlay = document.getElementById("fadeOverlay");
    var uString = loadComment(productId);
    content.innerHTML=uString;
    var popupAddComment = new Lightbox(btnClose, overlay, container, content);
    popupAddComment.show();

    popupAddComment.onContainerClick=function(e){
        var currentObj=e.target;
        var errorPopupContainer = document.getElementById("error-container");
        var controlPopupContainer = document.getElementById("CommentContainer");
        var managementComment = new ManagementComment();
        managementComment.initController(errorPopupContainer,controlPopupContainer);
        var link = currentObj.className.split(' ')[2];
        if(link=="btn_comment"){
            var uid=useridJSP;
            var proid=productId;
            var text= document.getElementById("comment-text");
            managementComment.saveNewComment(uid, proid, text, errorPopupContainer, controlPopupContainer);
        }
    }
}

function addToCart(obj) {
    if(!cart){
        cart=getCart();
    }
    var croot=cart.firstChild;
    if(obj.attributes["proID"]) {
        var productid = obj.getAttribute("proID");
        var productname = obj.getAttribute("proName");
        var productprice = obj.getAttribute("proPrice");
        var itemByDishExpression="//*[name()='Cart'][*[name()='ProductId']=" + productid + "]";
        var namespace ="";
        var root=cart.firstChild;
        var cartNameSpace=root.namespaceURI;
        if(cartNameSpace){
            namespace=cartNameSpace;
        }
        var count=croot.getElementsByTagName("Count")[0];
        if(count){
            var oldCount=parseInt(count.textContent);
            count.textContent=oldCount+1;
        }else{
            count=cart.createElementNS(namespace, "Count");
            count.textContent=1;
            croot.appendChild(count);
        }
        var itemByProdNode=getSingleNode(cart, itemByDishExpression);
        var oItem;
        if(!itemByProdNode){
            //create order item
            oItem=cart.createElementNS(namespace, "Cart");
            //set id and quantity
            var eProductid=cart.createElementNS(namespace, "ProductId");
            eProductid.textContent=productid;
            var eProductName=cart.createElementNS(namespace, "ProductName");
            eProductName.textContent=productname;
            var eQuantity=cart.createElementNS(namespace, "Quantity");
            eQuantity.textContent=1;
            var ePrice=cart.createElementNS(namespace, "Price");
            ePrice.textContent=productprice;
            var eTotalPrice=cart.createElementNS(namespace, "TotalPrice");
            eTotalPrice.textContent=(productprice*1);
            oItem.appendChild(eProductid);
            oItem.appendChild(eProductName);
            oItem.appendChild(eQuantity);
            oItem.appendChild(ePrice);
            oItem.appendChild(eTotalPrice);
            root.appendChild(oItem);
        }else{
            oItem=itemByProdNode;
            var quantityString=oItem.getElementsByTagName("Quantity")[0].textContent;
            var priceString=oItem.getElementsByTagName("Price")[0].textContent;
            var newQuan=parseInt(quantityString)+1;
            var oldPrice=parseInt(priceString);
            oItem.getElementsByTagName("Quantity")[0].textContent=newQuan;
            oItem.getElementsByTagName("TotalPrice")[0].textContent=(newQuan*oldPrice);
        }
        transformToCartView();

    }
}

function getCart() {
    var xhttp = getXmlHttpObj();
    var data = "action=REQUEST_CART";
    xhttp.open("GET", contextPath+"/FlowController?" + data, false);
    xhttp.send();
    var doc=xhttp.responseXML;
    return doc;
}

function transformToCartView() {
    if(cart&&xslProduct) {
        var params = [{
            name: "type",
            value: "cartView"
        }, {
            name: "contextpath",
            value: contextPath
        }];
        var cartView = transformXmlAndXsl(cart, xslProduct, params);
        var itemsContainer = document.getElementById("master-items-container");
        if (cartView) {
            itemsContainer.innerHTML = docfragToString(cartView);
        }
    }
}

function checkOut() {
    var data = "action=CHECK_OUT";
    var xhttp=getXmlHttpObj();
    xhttp.open("POST", contextPath+"/CheckOutController", true);
    xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
    xhttp.send(data);
    xhttp.onreadystatechange = function(e) {
        var currentObj = e.target;
        if(currentObj.readyState ==4&&currentObj.status==200) {
            var message=currentObj.responseXML;
            var error=message.getElementsByTagName("error")[0];
            var redirect=message.getElementsByTagName("redirect")[0];
            if (error) {
                var close=document.getElementById("btnClose");
                var overlay=document.getElementById("fadeOverlay");
                var container=document.getElementById("messageContainer");
                var content=document.getElementById("content");
                if(close&&overlay&&container&&content){
                    content.innerHTML=error.textContent;
                    var popup=new Lightbox(close, overlay, container, content);
                    popup.show();
                }
            }
            if(redirect){
                window.location.href=redirect.textContent;
            }
        }
    }
}
window.onunload=function(){
    saveCurrentOrderDocToSession(cart);
}
function isHaveUserDetail(){
    var xhttp=getXmlHttpObj();
    var data="action=HAVE_USER_DETAIL"
    xhttp.open("GET", contextPath+"/FlowController?"+data, false);
    xhttp.send();
    var doc=xhttp.responseText;
    return doc=="true";
}
function saveCurrentOrderDocToSession(pcart){
    if(pcart){
        var xhttp=getXmlHttpObj();
        var data="action=SAVE_ORDER_TO_SESSION&content="+XMLToString(pcart);
        xhttp.open("POST", contextPath+"/FlowController", false);
        xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
        xhttp.send(data);
    }
}

function loadComment(productId) {
    var xmlhttp;
    var data = "action=TRANSFORM_COMMENT&proid=" + productId;
    xmlhttp = getXmlHttpObj();
    xmlhttp.open("GET", contextPath+"/FlowController?"+data, false);
    xmlhttp.send();
    return xmlhttp.responseText;
}

function search(strSearch) {
    var param=[{
        name:"type",
        value:"searchProducts"
    },{
        name:"paramSearch",
        value: strSearch
    },{
        name:"contextpath",
        value: contextPath
    },{
        name:"checkUsername",
        value: userNameJSP
    }];
    var xmlProduct = loadSourceDoc("xml", "Products.xml");

    var view = transformXmlAndXsl(xmlProduct, xslProduct, param);
    var container= document.getElementById("productlistSearch");
    container.innerHTML = docfragToString(view);
}
